package service

import (
	"SecKill/common/define"
	"SecKill/common/models"
	"SecKill/common/response"
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

func AddVoucher(c *gin.Context) {
	var voucher models.Voucher
	if err := c.ShouldBindJSON(&voucher); err != nil {
		response.ResponseFail(c)
		return
	}
	if err := models.Db.Model(new(models.Voucher)).Create(&voucher).Error; err != nil {
		response.ResponseFail(c)
		return
	}
	response.ResponseOKWithData(c, "添加成功", voucher.Id, 1)
	return
}

func AddSeckillVoucher(c *gin.Context) {
	var voucher models.Voucher
	if err := c.ShouldBindJSON(&voucher); err != nil {
		response.ResponseFail(c)
		return
	}

	// 开启事务
	tx := models.Db.Begin()

	// 创建优惠券
	if err := tx.Model(new(models.Voucher)).Create(&voucher).Error; err != nil {
		tx.Rollback() // 发生错误时回滚
		response.ResponseFail(c)
		return
	}

	// 创建秒杀券
	var seckillVoucher models.SeckillVoucher
	seckillVoucher.VoucherId = voucher.Id
	seckillVoucher.Stock = voucher.Stock
	seckillVoucher.BeginTime = voucher.BeginTime
	seckillVoucher.EndTime = voucher.EndTime
	if err := tx.Model(new(models.SeckillVoucher)).Create(&seckillVoucher).Error; err != nil {
		tx.Rollback() // 发生错误时回滚
		response.ResponseFail(c)
		return
	}

	voucherId := strconv.Itoa(seckillVoucher.VoucherId)

	if err := models.RDb.Set(context.Background(), define.SECKILL_STOCK_KEY+voucherId, voucher.Stock, 0).Err(); err != nil {
		fmt.Println(err)
		tx.Rollback() // 发生错误时回滚
		response.ResponseFail(c)
		return
	}

	// 提交事务
	if err := tx.Commit().Error; err != nil {
		fmt.Println(err)
		tx.Rollback()
		response.ResponseFail(c)
		return
	}

	response.ResponseOKWithData(c, "添加成功", voucher.Id, 1)
	return
}

func QueryVoucherOfShop(c *gin.Context) {
	shopId, _ := strconv.Atoi(c.Param("shopId"))
	var voucherVoList []models.VoucherVo
	models.Db.Model(new(models.VoucherVo)).
		Table("tb_voucher v").
		Select("v.*, sv.stock, sv.begin_time, sv.end_time").
		Joins("left join tb_seckill_voucher sv on v.id = sv.voucher_id").
		Where("v.shop_id = ?", shopId).
		Find(&voucherVoList)
	response.ResponseOKWithData(c, "Success", voucherVoList, len(voucherVoList))
	return

}
